package net.wy.commons.util;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import javax.servlet.http.HttpServletRequest;

/**
 * IP工具
 * @author raymond
 *
 */
public class IPUtil {
	
	/**
	 * 获取IP
	 * @param request
	 * @return
	 */
	public static String getIp(HttpServletRequest request) {
		return request.getRemoteAddr();
	}
	
	/**
	 * 获取远程MAC地址
	 * @param request
	 * @return
	 */
	public static String getMACAddress(HttpServletRequest request){
		return getMACAddress(getIp(request));
	}
	
	/**
	 * 获取远程MAC地址
	 * @param ip
	 * @return
	 */
	public static String getMACAddress(String ip){
		if ("127.0.0.1".equals(ip)) {
			return "";
		}
		String str = "";
		String macAddress = "";
		try {
			Process p = Runtime.getRuntime().exec("nbtstat -A " + ip);
			InputStreamReader ir = new InputStreamReader(p.getInputStream());
			LineNumberReader input = new LineNumberReader(ir);
			for (int i = 1; i < 100; i++) {
				str = input.readLine();
				if (str != null) {
					if (str.indexOf("MAC") > 1) {
						macAddress = str.substring(str.length()-17);
						break;
					}
				}
			}
		} catch (IOException e) {
			e.printStackTrace(System.out);
		}
		return macAddress;
	}
}
